package com.mico.xchange.chaoex;

import com.mico.xchange.Exchange;
import com.mico.xchange.ExchangeFactory;
import com.mico.xchange.chaoex.dto.marketdata.ChaoexAssetPair;
import com.mico.xchange.chaoex.dto.trade.ChaoexLogin;
import com.mico.xchange.chaoex.dto.trade.results.ChaoexLoginResult;
import com.mico.xchange.chaoex.service.ChaoexAccountServiceRaw;
import com.mico.xchange.chaoex.service.ChaoexMarketDataServiceRaw;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ChaoexUtils {
    //炒客的交易对上送唯一标示，不做交易名称，存放ID
    private static Map<String,String> currencyMap = new HashMap<String,String>();
    private static Map<String,ChaoexLogin> tokenMap = new HashMap<String,ChaoexLogin>();

    /*
     *
     */
    public static void putCurrency(String coinNmae,String coinId){
        currencyMap.put(coinNmae,coinId);
    }

    /*
     *
     */
    public static String getCurrency(String coinName){
        try {
            if(currencyMap.keySet().size()==0){
                Exchange exchange = ExchangeFactory.INSTANCE.createExchange(ChaoexExchange.class.getName(), null, null);
                ChaoexMarketDataServiceRaw marketDataServiceRaw = (ChaoexMarketDataServiceRaw)exchange.getMarketDataService();
                    ChaoexAssetPair[] chaoexAssetPairs = marketDataServiceRaw.getAssetPairs();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return currencyMap.get(coinName);
    }

    public static ChaoexLogin getToken(String api_key, String api_secret, String pwd) throws Exception {
        ChaoexLogin chaoexLogin = tokenMap.get(api_key);
        if(chaoexLogin == null){
            chaoexLogin = getNewToken(api_key,api_secret,pwd);
        }
        if(chaoexLogin == null){
            chaoexLogin = getNewToken(api_key,api_secret,pwd);
        }
        if(chaoexLogin == null){
            throw new Exception("交易超时，请重试！");
        }
        return chaoexLogin;
    }

    public static ChaoexLogin getNewToken(String api_key, String api_secret, String pwd) throws Exception {
        Exchange exchange = ExchangeFactory.INSTANCE.createExchange(ChaoexExchange.class.getName(), null, api_secret);
        ChaoexAccountServiceRaw chaoexAccountService = (ChaoexAccountServiceRaw)exchange.getAccountService();
        ChaoexLoginResult result = chaoexAccountService.login(api_key,pwd);
        tokenMap.put(api_key,result.getResult());
        return result.getResult();
    }
}
